# coding:utf-8
import csv
import json
from datetime import datetime
from elasticsearch import Elasticsearch
import elasticsearch.helpers

es_host = ["10.222.1.55:9200"]
index_name = "devops"
doc_type = "mon-urls"
es = Elasticsearch(es_host)

def create_es():
    es.indices.create(index=index_name, body={"mappings": {doc_type: {"properties": {"web_name": {"type": "text"}, "web_url": {"type": "text"}}}}})

def import_es():

    with open('web-url.csv', 'r', encoding='utf-8-sig') as f:
        reader = csv.reader(f)
        id = 1
        for line in reader:
            str = json.dumps(line, ensure_ascii=False)
            list = json.loads(str)
            data = {
                "id": id,
                "web_name": list[0],
                "web_url": list[1]
            }
            es.index(index=index_name, doc_type=doc_type, body=data, id=id)
            id += 1

def get_url(field):
    res = es.search(index="devops", doc_type=doc_type, body={"_source": [field], "query":  {"wildcard" : { "web_name" : "?*" }}})
    results = []
    for item in res["hits"]["hits"]:
        # print(item["_source"])
        value = {}
        src = item["_source"]
        the_url=src[field]
        results.append(the_url)
    return results

def main():
    create_es()
    import_es()

if __name__ == "__main__":
    main()

